<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { getMenuTreeListApi, getDetilApi, saveApi, removeApi } from '@/api/system/menuApi'
import { useTable } from '@/hooks/web/useTable'
import { Table, TableColumn } from '@/components/Table'
import { ElMessage, ElPopconfirm } from 'element-plus'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { formatToDateTime } from '@/utils/dateUtil'

/**
 * 表格相关代码
 */
const useTableModule = () => {
  const { tableRegister, tableState, tableMethods } = useTable({
    fetchDataApi: async () => {
      const { currentPage, pageSize } = tableState
      const res = await getMenuTreeListApi({
        pageIndex: unref(currentPage),
        pageSize: unref(pageSize),
        ...unref(searchParams)
      })

      return {
        list: res.data,
        total: res.data.length
      }
    }
  })
  const { dataList, loading } = tableState
  const { getList } = tableMethods
  const tableColumns = reactive<TableColumn[]>([
    {
      field: 'index',
      label: '序号',
      type: 'index'
    },
    {
      field: 'name',
      label: '菜单名'
    },
    {
      field: 'createTime',
      label: '创建时间',
      width: 165,
      slots: {
        default: ({ row }) => <>{formatToDateTime(row.createTime)}</>
      }
    },
    {
      field: 'action',
      label: '操作',
      width: 240,
      slots: {
        default: ({ row }: any) => {
          return (
            <>
              <BaseButton type="primary" onClick={() => action(row, 'edit')}>
                编辑
              </BaseButton>
              <BaseButton type="success" onClick={() => action(row, 'detail')}>
                详情
              </BaseButton>
              <ElPopconfirm title="确定删除吗？" onConfirm={() => action(row, 'delete')}>
                {{
                  reference: () => <BaseButton type="danger">删除</BaseButton>
                }}
              </ElPopconfirm>
            </>
          )
        }
      }
    }
  ])

  return {
    tableRegister,
    tableColumns,
    dataList,
    loading,
    getList
  }
}
const { tableRegister, tableColumns, dataList, loading, getList } = useTableModule()

/**
 * 搜索相关代码
 */
const useSearchModule = (getList) => {
  const searchSchema = reactive<FormSchema[]>([
    {
      field: 'title',
      label: '',
      component: 'Input'
    }
  ])

  const searchParams = ref({})
  const setSearchParams = (data: any) => {
    searchParams.value = data
    getList(unref(searchParams))
  }

  return {
    searchSchema,
    searchParams,
    setSearchParams
  }
}
const { searchSchema, setSearchParams, searchParams } = useSearchModule(getList)

/**
 * 弹窗相关代码
 */
const useDialogModule = () => {
  const dialogVisible = ref(false)
  const dialogTitle = ref('')

  const currentRow = ref()
  const actionType = ref('')

  return {
    dialogVisible,
    dialogTitle,
    currentRow,
    actionType
  }
}
const { dialogVisible, dialogTitle, currentRow, actionType } = useDialogModule()

/**
 * 保存相关代码
 */
const useSaveDataModule = () => {
  const writeRef = ref<ComponentRef<typeof Write>>()

  const saveLoading = ref(false)

  const action = async (row: any, type: string) => {
    if (type === 'delete') {
      await removeApi(row.id)
      await getList()
      ElMessage.success('操作成功')
      return
    }

    dialogTitle.value = type === 'edit' ? '编辑' : '详情'
    actionType.value = type
    getDetilApi({ id: row.id }).then(({ data }) => {
      currentRow.value = data
    })
    dialogVisible.value = true
  }

  const AddAction = () => {
    dialogTitle.value = '添加'
    currentRow.value = undefined
    dialogVisible.value = true
    actionType.value = ''
  }

  const save = async () => {
    const write = unref(writeRef)
    if (!write) {
      return
    }

    const formData = await write?.submit()
    saveLoading.value = true
    await saveApi(formData)

    ElMessage.success('操作成功')

    saveLoading.value = false
    dialogVisible.value = false
    getList()
  }
  return {
    writeRef,
    saveLoading,
    action,
    AddAction,
    save
  }
}
const { saveLoading, action, AddAction, save, writeRef } = useSaveDataModule()
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">添加</BaseButton>
    </div>

    <Table
      :columns="tableColumns"
      node-key="id"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      header-align="center"
      :align="'center'"
      :border="false"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />
    <Detail v-if="actionType === 'detail'" :current-row="currentRow" />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        保存
      </BaseButton>
      <BaseButton @click="dialogVisible = false">关闭</BaseButton>
    </template>
  </Dialog>
</template>
